<template>
  <div class="user-list">
    <!-- 添加顶部栏 -->
    <div class="header-bar">
      <h2>用户管理</h2>
      <div class="user-info">
        <span>欢迎您，{{ currentUser.userName }}</span>
        <el-button type="danger" link @click="handleLogout">
          <el-icon><SwitchButton /></el-icon>退出登录
        </el-button>
      </div>
    </div>

    <!-- 搜索和操作栏 -->
    <div class="operation-bar">
      <div class="left">
        <el-input
          v-model="searchText"
          placeholder="请输入用户名搜索"
          class="search-input"
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch">
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>搜索
        </el-button>
        <el-switch
          v-model="showDeleted"
          @change="handleSearch"
          active-text="显示已删除"
          inactive-text="隐藏已删除"
          style="margin-left: 20px;"
          v-if="currentUser.userType === 'admin'" />
      </div>
      
      <el-button 
        type="success" 
        @click="handleAdd"
        v-if="currentUser.userType === 'admin'">
        <el-icon><Plus /></el-icon>新增用户
      </el-button>
    </div>

    <!-- 用户表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="userId" label="用户ID" width="180" align="center" />
        <el-table-column prop="userName" label="用户名" min-width="150" align="center" />
        <el-table-column prop="userType" label="用户类型" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getTagType(scope.row.userType)" effect="plain">
              {{ getUserTypeText(scope.row.userType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === '1' ? 'success' : 'danger'" effect="plain">
              {{ scope.row.status === '1' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="handleEdit(scope.row)"
              v-if="currentUser.userType === 'admin' || currentUser.userId === scope.row.userId">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button
              :type="scope.row.status === '1' ? 'warning' : 'success'"
              link
              @click="handleToggleStatus(scope.row)"
              v-if="currentUser.userType === 'admin' && currentUser.userId !== scope.row.userId">
              <el-icon><Switch /></el-icon>{{ scope.row.status === '1' ? '禁用' : '启用' }}
            </el-button>
            <el-button
              type="info"
              link
              @click="handleResetPassword(scope.row)"
              v-if="currentUser.userType === 'admin' && currentUser.userId !== scope.row.userId">
              <el-icon><Key /></el-icon>重置密码
            </el-button>
            <el-popconfirm
              title="确定删除该用户吗？"
              confirm-button-text="确定"
              cancel-button-text="取消"
              @confirm="handleDelete(scope.row)"
              v-if="currentUser.userType === 'admin' && currentUser.userId !== scope.row.userId">
              <template #reference>
                <el-button type="danger" link>
                  <el-icon><Delete /></el-icon>删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增用户' : '编辑用户'"
      width="500px"
      destroy-on-close
      @close="resetForm">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
        class="dialog-form">
        <el-form-item label="用户ID" prop="userId" v-if="dialogType === 'add'">
          <el-input v-model="formData.userId" placeholder="请输入用户ID" clearable />
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="formData.userName" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item 
          label="密码" 
          prop="password"
          :rules="dialogType === 'add' ? rules.password : rules.editPassword">
          <el-input 
            v-model="formData.password" 
            type="password" 
            placeholder="请输入密码"
            show-password />
          <div class="tip-text" v-if="dialogType === 'edit'">
            不修改密码请留空
          </div>
        </el-form-item>
        <el-form-item label="用户类型" prop="userType">
          <el-select v-model="formData.userType" placeholder="请选择用户类型" class="full-width">
            <el-option label="管理员" value="admin" />
            <el-option label="员工" value="employee" />
            <el-option label="普通用户" value="user" />
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱" clearable />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入手机号" clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Plus, Edit, Delete, SwitchButton, Switch, Key } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { getUserList, createUser, updateUser, deleteUser, updateUserStatus, resetPassword } from '@/api/userApi'

const router = useRouter()

// 表格数据
const tableData = ref([])
const loading = ref(false)
const submitLoading = ref(false)

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索
const searchText = ref('')
const showDeleted = ref(false)

// 对话框控制
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)

// 表单数据
const formData = reactive({
  userId: '',
  userName: '',
  password: '',
  userType: 'user',
  email: '',
  phone: ''
})

// 获取当前登录用户信息
const currentUser = ref(JSON.parse(localStorage.getItem('user') || '{}'))

// 表单验证规则
const rules = {
  userId: [
    { required: true, message: '请输入用户ID', trigger: 'blur' }
  ],
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  editPassword: [
  ],
  userType: [
    { required: true, message: '请选择用户类型', trigger: 'change' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ]
}

// 获取用户列表
const fetchUsers = async () => {
  loading.value = true
  try {
    const params = {}
    if (searchText.value) {
      params.keyword = searchText.value
    }

    const res = await getUserList(params)
    console.log('API返回数据:', res)

    if (res.code === 200 && res.data) {
      if (Array.isArray(res.data)) {
        // 根据开关决定是否显示已删除的用户
        let filteredUsers = res.data
        if (!showDeleted.value) {
          // 只显示启用状态的用户
          filteredUsers = res.data.filter(user => user.status === '1')
        }
        tableData.value = filteredUsers
        total.value = filteredUsers.length
      } else {
        console.error('返回数据格式不正确:', res.data)
        ElMessage.error('数据格式不正确')
      }
    } else {
      ElMessage.error(res.message || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchUsers()
}

// 添加用户
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  resetForm()
}

// 编辑用户
const handleEdit = (row) => {
  // 检查权限：只有管理员可以编辑所有用户，普通用户只能修改自己的信息
  if (currentUser.value.userType !== 'admin' && currentUser.value.userId !== row.userId) {
    ElMessage.warning('您没有权限修改其他用户的信息')
    return
  }

  dialogType.value = 'edit'
  dialogVisible.value = true
  const { password, ...rest } = row
  Object.assign(formData, rest)
  formData.password = '' // 清空密码字段
}

// 切换用户状态
const handleToggleStatus = async (row) => {
  // 检查权限：只有管理员可以切换用户状态
  if (currentUser.value.userType !== 'admin') {
    ElMessage.warning('只有管理员可以切换用户状态')
    return
  }

  // 不能禁用自己
  if (row.userId === currentUser.value.userId) {
    ElMessage.warning('不能禁用当前登录用户')
    return
  }

  const newStatus = row.status === '1' ? '0' : '1'
  const action = newStatus === '1' ? '启用' : '禁用'

  try {
    const res = await updateUserStatus(row.userId, newStatus, currentUser.value.userId)
    if (res.code === 200) {
      ElMessage.success(`${action}成功`)
      fetchUsers()
    } else {
      ElMessage.error(res.message || `${action}失败`)
    }
  } catch (error) {
    console.error(`${action}失败:`, error)
    ElMessage.error(`${action}失败`)
  }
}

// 重置密码
const handleResetPassword = async (row) => {
  // 检查权限：只有管理员可以重置密码
  if (currentUser.value.userType !== 'admin') {
    ElMessage.warning('只有管理员可以重置密码')
    return
  }

  // 不能重置自己的密码
  if (row.userId === currentUser.value.userId) {
    ElMessage.warning('不能重置当前登录用户的密码')
    return
  }

  ElMessageBox.prompt('请输入新密码', '重置密码', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputType: 'password',
    inputValidator: (value) => {
      if (!value || value.length < 6) {
        return '密码长度不能少于6位'
      }
      return true
    }
  }).then(async ({ value }) => {
    try {
      const res = await resetPassword(row.userId, { newPassword: value }, currentUser.value.userId)
      if (res.code === 200) {
        ElMessage.success('密码重置成功')
      } else {
        ElMessage.error(res.message || '密码重置失败')
      }
    } catch (error) {
      console.error('密码重置失败:', error)
      ElMessage.error('密码重置失败')
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 删除用户
const handleDelete = async (row) => {
  // 检查权限：只有管理员可以删除用户
  if (currentUser.value.userType !== 'admin') {
    ElMessage.warning('只有管理员可以删除用户')
    return
  }

  // 不能删除自己
  if (row.userId === currentUser.value.userId) {
    ElMessage.warning('不能删除当前登录用户')
    return
  }

  try {
    const res = await deleteUser(row.userId, currentUser.value.userId)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      if (tableData.value.length === 1 && currentPage.value > 1) {
        currentPage.value--
      }
      fetchUsers()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        // 构建提交数据
        const submitData = {
          userId: formData.userId,
          userName: formData.userName,
          userType: formData.userType,
          email: formData.email,
          phone: formData.phone
        }

        // 如果是新增或者编辑时修改了密码，则添加密码字段
        if (dialogType.value === 'add' || formData.password) {
          submitData.password = formData.password
        }

        let res
        if (dialogType.value === 'add') {
          res = await createUser(submitData, currentUser.value.userId)
        } else {
          res = await updateUser(formData.userId, submitData, currentUser.value.userId)
        }

        if (res.code === 200) {
          ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
          dialogVisible.value = false
          fetchUsers()
        } else {
          ElMessage.error(res.message || (dialogType.value === 'add' ? '添加失败' : '更新失败'))
        }
      } catch (error) {
        console.error(dialogType.value === 'add' ? '添加失败:' : '更新失败:', error)
        ElMessage.error(dialogType.value === 'add' ? '添加失败' : '更新失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchUsers()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchUsers()
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  formData.userId = ''
  formData.userName = ''
  formData.password = ''
  formData.userType = 'user'
  formData.email = ''
  formData.phone = ''
}

// 退出登录
const handleLogout = () => {
  localStorage.removeItem('user')
  localStorage.removeItem('token')
  router.push('/login')
  ElMessage.success('已退出登录')
}

// 获取用户类型显示文本
const getUserTypeText = (userType) => {
  const typeMap = {
    'admin': '管理员',
    'employee': '员工',
    'user': '普通用户'
  }
  return typeMap[userType] || userType
}

// 获取用户类型标签颜色
const getTagType = (userType) => {
  const typeMap = {
    'admin': 'danger',
    'employee': 'warning',
    'user': 'success'
  }
  return typeMap[userType] || 'info'
}

// 初始化
onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.user-list {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 40px);
}

.header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 20px;
  height: 60px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.header-bar h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.user-info span {
  color: #606266;
}

.operation-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.operation-bar .left {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 300px;
}

.table-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.table-card :deep(.el-card__body) {
  padding: 0;
}

.pagination {
  margin-top: 20px;
  padding: 15px;
  display: flex;
  justify-content: flex-end;
  background: #fff;
  border-top: 1px solid #ebeef5;
}

.dialog-form {
  padding: 20px 20px 0;
}

.dialog-footer {
  padding: 20px 0 10px;
  text-align: right;
}

.tip-text {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.2;
}

.full-width {
  width: 100%;
}

:deep(.el-table) {
  border-radius: 8px 8px 0 0;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa !important;
}

:deep(.el-button + .el-button) {
  margin-left: 8px;
}

:deep(.el-tag) {
  min-width: 80px;
}
</style>
